package com.lnking.lnkingplace.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lnking.lnkingplace.Util.UserUtil;
import com.lnking.lnkingplace.mapper.ActivityMapper;
import com.lnking.lnkingplace.mapper.FileListMapper;
import com.lnking.lnkingplace.model.dto.activity.ActivityDetailDto;
import com.lnking.lnkingplace.model.dto.activity.ActivityDto;
import com.lnking.lnkingplace.model.dto.user.UserDetailDto;
import com.lnking.lnkingplace.model.dto.user.UserDto;
import com.lnking.lnkingplace.model.entity.Activity;
import com.lnking.lnkingplace.model.entity.FileList;
import com.lnking.lnkingplace.model.entity.RecordUser;
import com.lnking.lnkingplace.model.request.activity.ActivityAddRequest;
import com.lnking.lnkingplace.model.request.activity.ActivityUpdateRequest;
import com.lnking.lnkingplace.service.IActivityService;
import com.lnking.starter.mybatis.service.impl.CustomServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sn
 * @since 2022-08-19
 */
@Service
public class ActivityServiceImpl extends CustomServiceImpl<ActivityMapper, Activity> implements IActivityService {

    @Value("${upload.file-path-prefix}")
    String filePathPrefix;

    @Resource
    FileListMapper fileListMapper;

    @Autowired
    UserUtil userUtil;

    @Override
    public void add(ActivityAddRequest params) throws Exception {
        Assert.isTrue(params.getEndTime().isAfter(params.getStartTime()),"活动结束时间应该在开始后");
        Activity entity = new Activity();
        BeanUtils.copyProperties(params, entity);
        UserDto user = userUtil.getUser();
          entity.setPlaceId(user.getPlaceId());
        getBaseMapper().insert(entity);
    }

    @Override
    public void update(ActivityUpdateRequest params) {
        Assert.isTrue(params.getEndTime().isAfter(params.getStartTime()),"活动结束时间应该在开始后");
        Activity entity = new Activity();
        BeanUtils.copyProperties(params, entity);
        getBaseMapper().updateById(entity);
    }

    @Override
    public ActivityDetailDto getDetailById(String id) {
        ActivityDetailDto activity = getBaseMapper().getDetailById(id);

        // 把所有的图片附件查询出来
        QueryWrapper<FileList> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(FileList::getId, activity.getPhotos().split(";"));
        List<FileList> certificateList = fileListMapper.selectList(wrapper);
        certificateList.stream().forEach(item -> item.setPath(filePathPrefix + item.getPath()));
        activity.setCertificateList(certificateList);
        return activity;
    }
}
